package cn.fl.capital.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapFundQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.service.ICapFundInsIncomeService;
import cn.fl.capital.service.ICapFundService;
import cn.fl.capital.utils.ImportFundList;
import cn.fl.capital.vo.CapFundVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.insurance.vo.InsCapFundVO;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
* @Description:    资金管理--保险来款管理controller
* @Author:         liurong
* @CreateDate:     2018/12/13 18:11
* @Version:        1.0
*/
@Controller
@RequestMapping("/capital/capFundInsIncome")
public class CapFundInsIncomeController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CapFundInsIncomeController.class);

    // 上传最大处理的数据量
    private static final int MAX_SIZE = 1000;

    @Autowired
	private ICapFundService capFundService;
	@Autowired
	private ICapFundInsIncomeService capFundInsIncomeService;
	/**
	 * 到保险来款管理页面
	 * @return
	 */
	@RequestMapping(value = "/toManagePage.do", method = {RequestMethod.GET})
	public ModelAndView toManagePage() {
		BaseLogUtils.info(logger, "toManagePage", "跳转到保险来款管理页面...", CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("capital/capFundInsIncome/capFundInsIncomeMain");
		return view;
	}

	/**
	 * Tab页面切换控制方法
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/enterTabPage.do", method = {RequestMethod.GET})
	public ModelAndView enterTabPage(HttpServletRequest request) {
		String type = request.getParameter("type");
		ModelAndView view = null;
		if ("1".equals(type)) {
			BaseLogUtils.info(logger, "enterTabPage", "加载到保险来款核销列表页面.", CurrentThreadContext.getCurrentUserName());
			view = new ModelAndView("capital/capFundInsIncome/insIncomeVerificationList");
		} else if ("2".equals(type)) {
			BaseLogUtils.info(logger, "enterTabPage", "加载到保险来款记录列表页面.", CurrentThreadContext.getCurrentUserName());
			view = new ModelAndView("capital/capFundInsIncome/insIncomeRecordList");
		} else {

		}
		return view;
	}

	/**
	 * 保险来款核销列表数据
	 * @param request
	 * @param condition
	 * @return
	 */
	@RequestMapping(value = "/verificationList.do", method = {RequestMethod.GET})
	@ResponseBody
	public Object verificationList(HttpServletRequest request, CapFundQueryCondition condition) {
		int totalCount = 0;
		List<CapFundVO> list = null;
		try {
			Pager page = packageQueryCondition(request, condition, "1");

			Pager pager = capFundService.searchListPage(page);
			if (pager != null) {
				list = (List<CapFundVO>) pager.getResultList();
				totalCount = pager.getTotalCount();
			}
		} catch (Exception e) {
			BaseLogUtils.error(logger, "verificationList", "初始化保险来款核销列表数据异常", e);
		}

		ListPageVO<CapFundVO> listPage = new ListPageVO<CapFundVO>(list, totalCount);
		return listPage;
	}

	/**
	 * 保险来款记录列表数据
	 * @param request
	 * @param condition
	 * @return
	 */
	@RequestMapping(value = "/recordList.do", method = {RequestMethod.GET})
	@ResponseBody
	public Object recordList(HttpServletRequest request, CapFundQueryCondition condition) {
		int totalCount = 0;
		List<CapFundVO> list = null;
		try {
			Pager page = packageQueryCondition(request, condition, "2");

			Pager pager = capFundService.searchListPage(page);
			if (pager != null) {
				list = (List<CapFundVO>) pager.getResultList();
				totalCount = pager.getTotalCount();
			}
		} catch (Exception e) {
			BaseLogUtils.error(logger, "recordList", "初始化保险来款记录列表数据异常", e);
		}

		ListPageVO<CapFundVO> listPage = new ListPageVO<CapFundVO>(list, totalCount);
		return listPage;
	}

	/**
	 * 下载模板文件
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/downloadTemp.do",produces="application/octet-stream;charset=UTF-8")
	public ResponseEntity<byte[]> downloadTemplate(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		try {
			String filename = "insIncomeTemp.txt";

			String url = session.getServletContext().getRealPath("/") + "resource/template/capital/" + filename;

			HttpHeaders headers = new HttpHeaders();
			File file = new File(url);

			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			headers.setContentDispositionFormData("attachment", filename);

			return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
					headers, HttpStatus.CREATED);
		} catch (Exception e) {
			BaseLogUtils.error(logger, "downloadTemplate", "下载模板文件异常", e);
		}
		return null;
	}

	/**
	 * 批量导入
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/insIncomeImport.do", method = { RequestMethod.POST})
	@ResponseBody
	public DataResultVO insIncomeImport(HttpServletRequest request, HttpServletResponse response) {
		DataResultVO resultVO = new DataResultVO();
		try {
			String filePath = request.getParameter("filePath");
			if (StringUtils.isBlank(filePath)) {
				throw new BaseException("请先上传“每月还款明细”文件");
			}

			List<InsCapFundVO> list = ImportFundList.importInsIncomeTxt(filePath);
			if (CollectionUtils.isEmpty(list)) {
				throw new BaseException("文件中未读取到有效的数据！");
			}
			if (list.size() > MAX_SIZE) {
				throw new BaseException("单次最大处理" + MAX_SIZE + "条数据！");
			}
			boolean flag = capFundInsIncomeService.batchAddImport(list);
			if (flag) {
				resultVO.setSuccess(BaseConstant.IS_YESNO_YES);
				resultVO.setInfo("总数：" + list.size() + "，导入成功：" + list.size() + "，保险来款导入成功！");
			} else {
				// 后台接口是要么都成功，要么都失败
				throw new BaseException("总数：" + list.size() + "，导入成功：" + 0 + "，保险来款导入失败！");
			}
		} catch (BaseException e) {
			resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
			resultVO.setInfo(e.getMessage());
		} catch (Exception e) {
			BaseLogUtils.error(logger, "insIncomeImport", "批量导入保险来款数据异常", e);
			resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
			resultVO.setInfo(e.getMessage());
		}

		return resultVO;
	}

	/**
	 * 封装列表查询参数
	 * @param request
	 * @param condition
	 * @param qType
	 * 			"1":查询保险来款核销列表
	 * 			"2":查询保险来款记录列表
	 * @return
	 * @throws Exception
	 */
	private Pager packageQueryCondition(HttpServletRequest request, CapFundQueryCondition condition, String qType) throws Exception {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		condition = setNullValue(condition);
		// 资金状态集合 CAP0004：0.未分解1.分解中2.已分解3.已作废4.冲红中5.已冲红6.已转出 7.减免中 8.已减免 9.已冻结
		List<String> fundStatusList = new ArrayList<>();
		if ("1".equals(qType)) {
			fundStatusList.add(CapitalConstant.CODE_CAP_FUND_STS_CD_0);
			fundStatusList.add(CapitalConstant.CODE_CAP_FUND_STS_CD_1);
		} else if ("2".equals(qType)) {
			//fundStatusList.add(CapitalConstant.CODE_CAP_FUND_STS_CD_2);
		}
		condition.setFundStatusCdList(fundStatusList);
		condition.setSortName("crtTm");
		condition.setSortOrder("desc");
		// 查询资金录入方式：2.批量导入
		condition.setFundInputCd(CapitalConstant.CODE_CAP_FUND_INPUT_CD_2);
		// 资金种类CAP0014：1-保险租金
		condition.setFundTypCd(CapitalConstant.CODE_CAP_FUND_TYP_CD_1);
		page.setCondition(condition);

		return page;
	}

	/**
	 * 将对象中为空字符串的属性置为null
	 *
	 * @param source
	 * @return
	 * @throws
	 * @author liurong
	 * @date 2018/11/2 8:56
	 */
	private <T> T setNullValue(T source) throws IllegalArgumentException, IllegalAccessException, SecurityException {
		Field[] fields = source.getClass().getDeclaredFields();
		for (Field field : fields) {
			if (field.getGenericType().toString().equals("class java.lang.String")) {
				field.setAccessible(true);
				Object obj = field.get(source);
				if (obj != null && obj.equals("")) {
					field.set(source, null);
				}
			}
		}
		return source;
	}

}
